package com.yantong.controller.locallife;

import com.alibaba.fastjson.JSONObject;
import com.yantong.annotation.Log;
import com.yantong.constant.MemberType;
import com.yantong.controller.BaseController;
import com.yantong.exception.BDException;
import com.yantong.mapper.CarMapper;
import com.yantong.pojo.*;
import com.yantong.pojo.vo.ImgVo;
import com.yantong.result.ResultVo;
import com.yantong.service.*;
import com.yantong.utils.DateUtils;
import com.yantong.utils.PageUtils;
import com.yantong.utils.ValidateUtil;
import com.yantong.utils.excel.ExcelHelper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;


/**
 * 门店列表
 *
 * @author xiangyi
 * @version V1.0.0
 * @Description:
 * Copyright: Copyright (c) 2018
 * @date 2018年9月7日 下午1:53:58
 * @since 3.0
 */
@Controller
@RequestMapping("/commanderList/manage")
public class CommanderListController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(CommanderListController.class);

    private static final String prefix = "commander/manage";

    @Autowired
    private MemberService memberService;

    @Autowired
    private CommanderListService commanderListService;

    @Autowired
    private RegCommanderService regCommanderService;

    @Autowired
    private OrderService orderService;


    @Autowired
    private CarMapper carMapper;
    @Autowired
    private StoreService storeService;
    @Autowired
    private IndustryBrandService industryBrandService;

    /**
     * 门店列表界面
     *
     * @param model
     * @return
     */
    @GetMapping()
    @RequiresPermissions("commanderList:manage:manage")
    public String commanders(Model model) {
        model.addAllAttributes(getCentreIdModelInfo());
        return prefix + "/commanderLists";
    }

    /**
     * 门店列表界面
     *
     * @param model
     * @return
     */
    @GetMapping("/tableList/{id}")
    @RequiresPermissions("commanderList:manage:manage")
    public String tableList(@PathVariable Long id, Model model) {
        model.addAttribute("teamId", id);
        return prefix + "/tableList";
    }



    /**
     * 跳转页面：选择商品页面
     *
     * @return
     */
    @GetMapping("/toChooseCoupon")
    @RequiresPermissions("activit:manage:chooseproduct")
    public String toChooseCoupon(Model model, Long teamId) {
        ListMemberParams listMemberParams = new ListMemberParams();
        if (getUserCentreId() != null) {
            listMemberParams.setCentreId(getUserCentreId());
        }

        Map<String, Object> map = getCentreIdModelInfo();
        model.addAttribute("teamId", teamId);
        model.addAllAttributes(map);
        return prefix + "/chooseCoupon";
    }

    /**
     * 桌子新增页面
     *
     * @param model
     * @return
     */
    @GetMapping("/toInsertTable")
    @RequiresPermissions("commanderList:manage:manage")
    public String toInsertTable(Long teamId, Model model) {
        model.addAttribute("teamId", teamId);
        return prefix + "/insertTable";
    }

    /**
     * 桌子修改页面
     *
     * @param model
     * @return
     */
    @GetMapping("/toFreeChargeInfoAdd")
    @RequiresPermissions("commanderList:manage:manage")
    public String toFreeChargeInfoAdd(Long mid, Model model) {
        model.addAttribute("teamId", mid);
        Store store = storeService.getStoreByTeamid(mid);
        if (null != store) {
            model.addAttribute("freechargeDesc", store.getFreechargeDesc());
            model.addAttribute("notice", store.getNotice());
            model.addAttribute("shopEnv", store.getShopEnv());
            model.addAttribute("discountRule", store.getDiscountRule());
        }
        return prefix + "/addFreechargeInfo";
    }

    /**
     * 门店列表
     *
     * @param listMemberParams
     * @param member
     * @param offset
     * @param limit
     * @return
     */
    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("commanderList:manage:manage")
    public PageUtils<Member> listCommanders(ListMemberParams listMemberParams, Member member, int offset, int limit) {
        if (listMemberParams.getCentreId() == null) {
            listMemberParams.setCentreId(getUserCentreId());
        }
        if (listMemberParams.getLiansuoId() == null && ValidateUtil.isNotEmptyObjectOrString(getUserTeamId())) {
            listMemberParams.setLiansuoId(getUserTeamId());
        }
        return commanderListService.listCommanders(listMemberParams, member, offset, limit);
    }




    /**
     * 门店列表
     *
     * @param listMemberParams
     * @param member
     * @return
     */
    @ResponseBody
    @GetMapping("/listCommanders")
    public List<Member> listCommanders(ListMemberParams listMemberParams, Member member) {
        if (listMemberParams.getCentreId() == null) {
            listMemberParams.setCentreId(getUserCentreId());
        }
        return commanderListService.listCommanders(listMemberParams, member);
    }

    /**
     * 取消门店弹框
     *
     * @param id
     * @param model
     * @return
     */
    @RequiresPermissions("commanderList:manage:cancel")
    @GetMapping("/cancelCommander/{id}")
    public String cancelCommander(@PathVariable Long id, Model model) {
        model.addAttribute("id", id);
        return prefix + "/cancelCommander";
    }


    /**
     * 取消门店
     *
     * @param member
     * @return
     */
    @Log(module = "门店管理", operation = "取消门店")
    @ResponseBody
    @RequiresPermissions("commanderList:manage:cancel")
    @PostMapping("/cancelCommanderUpdate")
    public ResultVo cancelCommanderUpdate(Member member) {
        if (member == null || member.getId() == null) {
            return ResultVo.error();
        }
        member.setIsteam(MemberType.NORMAL.getCode());
        member.setCloseTime(new Date());
        if (memberService.cancelCommanderUpdate(member) < 1) {
            return ResultVo.error();
        }
        return ResultVo.ok();
    }

    /**
     * 打烊设置
     *
     * @param id
     * @param model
     * @return
     */
    @RequiresPermissions("commanderList:manage:closeSet")
    @GetMapping("/closeSet/{id}")
    public String closeSet(@PathVariable Long id, Model model) {
        model.addAttribute("member", memberService.getDetail(id));
        return prefix + "/closeSet";
    }

    /**
     * 门店下面的用户
     *
     * @param id
     * @param model
     * @return
     */
    @RequiresPermissions("commanderList:manage:teamuser")
    @GetMapping("/toTeamUser/{id}")
    public String toTeamUser(@PathVariable Long id, Model model) {
        model.addAttribute("id", id);
        return "member/manage/membertheuser";
    }

    /**
     * 打烊设置
     *
     * @param member
     * @return
     */
    @Log(module = "门店管理", operation = "打烊设置")
    @ResponseBody
    @RequiresPermissions("commanderList:manage:closeSet")
    @PostMapping("/closeSet")
    public ResultVo closeSet(Member member) {
        if (member == null || member.getId() == null) {
            return ResultVo.error();
        }
        member.setSleepStartTime(DateUtils.getSleepDateFormat(member.getSleepStartTime()));
        member.setSleepEndTime(DateUtils.getSleepDateFormat(member.getSleepEndTime()));
        member.setSleepTime(new Date());
        if (memberService.updateMember(member) < 1) {
            return ResultVo.error();
        }
        return ResultVo.ok();
    }

    /**
     * 开通时间设置
     *
     * @param id
     * @param model
     * @return
     */
    @RequiresPermissions("commanderList:manage:checkTimeSet")
    @GetMapping("/checkTimeSet/{id}")
    public String checkTimeSet(@PathVariable Long id, Model model) {
        model.addAttribute("member", memberService.getDetail(id));
        return prefix + "/checkTimeSet";
    }

    /**
     * 开通时间设置
     *
     * @param member
     * @return
     */
    @Log(module = "门店管理", operation = "开通时间设置")
    @ResponseBody
    @RequiresPermissions("commanderList:manage:checkTimeSet")
    @PostMapping("/checkTimeSet")
    public ResultVo checkTimeSet(Member member) {
        if (member == null || member.getId() == null) {
            return ResultVo.error();
        }
        if (memberService.updateMember(member) < 1) {
            return ResultVo.error();
        }
        return ResultVo.ok();
    }

    /**
     * 编辑门店
     *
     * @param id
     * @param model
     * @return
     */
    @RequiresPermissions("commanderList:manage:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable Long id, Model model) {
        Member member = memberService.getDetail(id);
        Order order = new Order();
        order.setMid(id);
        Integer orderSum = orderService.countByOrder(order);
        member.setOrderSum(orderSum);
        member.setLat(member.getLng() + "," + member.getLat());
        IsteamDesc isteamDesc = regCommanderService.getIsteamDesc(member.getIsteamDesc());
        member.setTeamDesc(isteamDesc);
        HashMap hashMap = new HashMap();
        hashMap.put("centreId",getUserCentreId());
//        List<Industry> industryList = industryService.selectByList(hashMap);
//        model.addAttribute("industrys", industryList);
        model.addAttribute("industryBrands",industryBrandService.listByCentreId(hashMap));
        model.addAttribute("member", member);
        model.addAllAttributes(getCentreIdModelInfo());
        return prefix + "/editCommander";
    }


    /**
     * 编辑门店
     *
     * @return
     */
    @Log(module = "门店管理", operation = "编辑门店")
    @ResponseBody
    @RequiresPermissions("commanderList:manage:edit")
    @PostMapping("/edit")
    public ResultVo edit(Member member) {
        if (member == null || member.getId() == null) {
            return ResultVo.error();
        }
        ImgVo imgVo = new ImgVo();
        List<String> list = new ArrayList<String>();
        list.add(member.getIdCardZ().equals("") ? "" : member.getIdCardZ());
        list.add(member.getIdCardF().equals("") ? "" : member.getIdCardF());
        list.add(member.getStore().equals("") ? "" : member.getStore());
        imgVo.setRemark(member.getRemark().equals("") ? "" : member.getRemark());
        imgVo.setImages(list);
        member.setIsteamDesc(JSONObject.toJSONString(imgVo));
        if (StringUtils.isNotEmpty(member.getLat())) {
            String[] str = member.getLat().split(",");
            if (str != null && str.length >= 2) {
                member.settLng(str[0]);
                member.settLat(str[1]);
            } else {
                member.settLng("");
                member.settLat("");
            }
        } else {
            member.settLng("");
            member.settLat("");
        }
        member.setLat(null);

        if( member.getIndustryBrandId() == null){
            member.setIndustryBrandId(0L);
        }

        if (memberService.updateMember(member) < 1) {
            return ResultVo.error();
        }

        return ResultVo.ok();
    }


    /**
     * 设置员工店主
     *
     * @param model
     * @return
     */
    @Log(module = "门店管理", operation = "设置员工店主")
    @ResponseBody
    @RequiresPermissions("commanderList:manage:edit")
    @PostMapping("/setStaff")
    public ResultVo setStaff(Member member) {
        if (member == null || member.getId() == null) {
            return ResultVo.error();
        }
        if (memberService.updateMember(member) < 1) {
            return ResultVo.error();
        }
        return ResultVo.ok();
    }

    /**
     * 门店列表-导出
     *
     * @param response
     * @param listMemberParams
     * @param member
     */
    @RequiresPermissions("commanderList:manage:export")
    @GetMapping("/exportCommander")
    public void exportCommander(HttpServletResponse response, ListMemberParams listMemberParams, Member member) {
        List<List<Object>> resultData = new ArrayList<>();
        String[] head = {"门店ID", "门店昵称", "门店姓名", "门店手机", "推荐门店", "开通时间", "保证金", "团员数量", "区", "门店地址", "小区", "经纬度", "所属路线", "余额", "门店批次", "申请统计"};
        resultData.add(0, Arrays.asList(head));
        if (listMemberParams.getCentreId() == null) {
            listMemberParams.setCentreId(getUserCentreId());
        }
        List<Member> list = commanderListService.listCommanders(listMemberParams, member);
        if (CollectionUtils.isNotEmpty(list)) {
            for (Member mem : list) {
                List<Object> row = new ArrayList<>();
                row.add(mem.getId());
                row.add(mem.getNickname() != null ? mem.getNickname() : "");
                row.add(mem.getRealname() != null ? mem.getRealname() : "");
                row.add(mem.getMobile() != null ? mem.getMobile() : "");
                row.add(mem.getUpTeamname() != null ? mem.getUpTeamname() : "");
                row.add(mem.getCheckTime() != null ? DateUtils.format(mem.getCheckTime(), "yyyy-MM-dd HH:mm:ss") : "");
                row.add(mem.getBondmoney() != null ? mem.getBondmoney() : "");
                row.add("");
                row.add(mem.gettArea() != null ? mem.gettArea() : "");
                String adress = "";
                if (mem.gettProvince() != null) adress += mem.gettProvince();
                if (mem.gettCity() != null) adress += mem.gettCity();
                if (mem.gettArea() != null) adress += mem.gettArea();
                if (mem.gettXiaoqu() != null) adress += mem.gettXiaoqu();
                row.add(adress);
                row.add(mem.gettXiaoqu() != null ? mem.gettXiaoqu() : "");
                String jxd = "";
                if (mem.getLng() != null) jxd += mem.getLng() + ",";
                if (mem.getLat() != null) jxd += mem.getLat();
                row.add(jxd);
                //CarXq carXq = carXqService.getCarXqByXqName(mem.gettXiaoqu());
                Car car = carMapper.getByTmid(mem.getId());
                if (car != null) {
                    row.add(car.getUsername());
                } else {
                    row.add("");
                }

                row.add(mem.getCredit2() != null ? mem.getCredit2() : "");
                row.add(mem.getTeamNum() != null && mem.getTeamNum() > 0 ? mem.getTeamNum() : "最新批次");
                row.add(mem.getsTime() != null ? DateUtils.format(mem.getsTime(), "yyyy-MM-dd HH:mm:ss") : "");
                resultData.add(row);
            }
            String fileName = "门店列表_" + DateUtils.format(new Date(), "yyyyMMddHHmmss");
            try {
                ExcelHelper.exportExcel(response, fileName, "门店列表", resultData);
            } catch (IOException e) {
                logger.info("export member error:{}", e.getMessage());
            }
        }
    }



}
